package cn.liberals.user.service.impl;

import cn.liberals.basic.constant.BaseConstants;
import cn.liberals.basic.exception.BusinessException;
import cn.liberals.basic.utils.MD5Utils;
import cn.liberals.basic.utils.StrUtils;
import cn.liberals.basic.vo.RegisterInEmailVo;
import cn.liberals.basic.vo.RegisterVo;
import cn.liberals.user.domain.Logininfo;
import cn.liberals.user.domain.User;
import cn.liberals.user.mapper.LogininfoMapper;
import cn.liberals.user.mapper.UserMapper;
import cn.liberals.user.service.IUserService;
import cn.liberals.basic.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liberals
 * @since 2022-07-06
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;

    /*
    * @Title: phoneCodeResister
    * @Description: 手机注册
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/12 23:50
    * @Parameters:
    * @Return
    */
    @Override
    public void phoneCodeResister(RegisterVo registerVo) {
        String phone = registerVo.getPhone();
        String phoneCodeValue = registerVo.getPhoneCodeValue();
        String password = registerVo.getPassword();
        String confirmPassword = registerVo.getConfirmPassword();
        // 为空校验
        if (StringUtils.isEmpty(phone)
            ||   StringUtils.isEmpty(phoneCodeValue)
            || StringUtils.isEmpty(password)
            || StringUtils.isEmpty(confirmPassword)
        ){
            throw new BusinessException("参数不能为空");
        }

        String phoneCodeKey = BaseConstants.verifyCodeConstant.BUSINESS_REGISTER_KEY + phone;
        Object phoneCodeValueRedis = redisTemplate.opsForValue().get(phoneCodeKey);
        // 两次手机号是否一致
        if (phoneCodeValueRedis == null) {
            throw new BusinessException("验证码已失效，请重新获取！");
        }
        // 判断验证码是否正确
        String phoneCode = phoneCodeValueRedis.toString().split(":")[1];
        if (!phoneCode.equalsIgnoreCase(phoneCodeValue)) {
            throw new BusinessException("手机验证码错误，请重新输入！");
        }
        // 两次密码是否一致
        if (!password.equals(confirmPassword)) {
            throw new BusinessException("两次密码不一致，请重新输入！");
        }
        //判断用户是否已注册，如果已注册提示用户
        User user = userMapper.loadByPhone(phone);
        if (user != null) {
            throw new BusinessException("用户已注册，请直接登录，如果忘记密码，请点击忘记密码！");
        }
        // 初始化user表,就是对你的user对象进行赋值操作
        user = smsCodeDto2User(registerVo);
        // 保存user表
        userMapper.save(user);
        // 保存logininfo
        Logininfo logininfo = user2Logininfo(user);
        logininfoMapper.save(logininfo);
        // 将logininfo主键设置到user表，并修改
        user.setLogininfoId(logininfo.getId());
        userMapper.update(user);
    }

    /*
    * @Title: registerEmail
    * @Description: 邮箱注册
    * @Author: liberals
    * @Version: 1.0
    * @Date:  2022/7/12 23:50
    * @Parameters:
    * @Return
    */
    @Override
    public void registerEmail(RegisterInEmailVo registerInEmailVo) {
        String email = registerInEmailVo.getEmail();
        String emailCodeValue = registerInEmailVo.getEmailCodeValue();
        String password = registerInEmailVo.getPassword();
        String confirmPassword = registerInEmailVo.getConfirmPassword();
        // 1.判断参数是否为空
        if (StringUtils.isEmpty(email)||StringUtils.isEmpty(password)||StringUtils.isEmpty(confirmPassword)||StringUtils.isEmpty(emailCodeValue)){
            throw new BusinessException("输入参数为空，请重新输入！");
        }
        // 2.判断两次邮箱是否一致
        String emailVerifyCodeKey = BaseConstants.verifyCodeConstant.BUSINESS_REGISTER_KEY +":"+ email;
        Object emailVerifyCodeValueTemp = redisTemplate.opsForValue().get(emailVerifyCodeKey);
        String emailVerifyCodeValue = emailVerifyCodeValueTemp.toString().split(":")[1];
        if(emailVerifyCodeValueTemp==null) {
            throw new BusinessException("验证码已失效，请重新获取！");
        }
        // 3.判断验证码是否正确
        if(!emailVerifyCodeValue.equalsIgnoreCase(emailCodeValue)){
            throw new BusinessException("验证码输入错误，请重新输入！");
        }
        // 4.判断此邮箱是否已经注册
        User user = userMapper.loadByEmail(email);
        if(user!=null){
            throw new BusinessException("此邮箱已被注册，请重新输入！");
        }
        // 5.判断两次密码是否一致
        if(!password.equals(confirmPassword)){
            throw new BusinessException("两次密码输入不一致，请重新输入！");
        }
        // 6.密码加盐加密，设置到数据库
        User user1 = initEmailUser(registerInEmailVo);
        userMapper.save(user1);
        // 7.调用User2LoginInfo方法，把转化为loginInfo对象，添加到loginInfo表中
        Logininfo logininfo = user2Logininfo(user1);
        logininfoMapper.save(logininfo);
        user1.setLogininfoId(logininfo.getId());
        userMapper.update(user1);
    }


    @Override
    public User loadByLogininfoId(Long logininfoId) {
        return userMapper.loadByLogininfoId(logininfoId);
    }



    public User initEmailUser(RegisterInEmailVo registerInEmailVo){
        String salt = StrUtils.getComplexRandomString(32);
        String passwordTmp = salt + registerInEmailVo.getPassword();
        User user1 = new User();
        user1.setUsername(registerInEmailVo.getEmail());
        user1.setEmail(registerInEmailVo.getEmail());
        user1.setSalt(salt);
        user1.setPassword(passwordTmp);
        return user1;
    }


    /*
     * @Title: registerVo2User
     * @Description: 设置user对象数据
     * @Author: liberals
     * @Version: 1.0
     * @Date:  2022/7/6 18:45
     * @Parameters:
     * @Return
     */
    public User smsCodeDto2User(RegisterVo registerVo) {
        // 将设置的值传到user对象中
        String phone = registerVo.getPhone();
        // 因为用的手机号注册所以说用户名称就是手机号
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 将明文密码用md5加密
        String salt = StrUtils.getComplexRandomString(32);
        String saltPassword = MD5Utils.encrypByMd5(salt + registerVo.getPassword());
        // 设置加盐加密后的密码，盐值
        user.setPassword(saltPassword);
        user.setSalt(salt);
        return user;
    }

    public Logininfo user2Logininfo(User user) {
        // 利用工具类拷贝数据到Logininfo中
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        // 设置数据类型为用户
        logininfo.setType(1);
        return logininfo;
    }

}
